import router from '@/router'
// import { getToken } from './utils/auth'
import store from '@/store'
import { asyncRoutes } from './router/asyncRoutes'
function getMunesList(permission) {
  // 将后台返回的权限字符串分割成数组。
  const arr = permission.map(item => item.split(':'))
  return {
    menus: [...new Set(arr.map(item => item[0]))],
    smenus: [...new Set(arr.map(item => `${item[0]}:${item[1]}`))]
  }
}
function getFilterRoutes(menusList, asyncRoutes) {
  // 如果是管理员不做任何过滤
  if (menusList.smenus.includes('*:*')) return asyncRoutes

  const filterRoutes = asyncRoutes.filter(route => menusList.menus.includes(route.permission)).map(item => ({
    ...item,
    children: item.children.filter(item => menusList.smenus.includes(item.permission))
  }))
  return filterRoutes
}
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 判断用户信息里面是否有id，也就是为了检查是否需要请求接口。
      if (!store.state.user.userInfo.id) {
        // 接口返回的是当前账号的权限信息
        const permission = await store.dispatch('user/getuserinfo')

        // 将权限信息里面的一级路由信息二级分离出来。
        const menusList = getMunesList(permission)

        // 留下与自身权限匹配的动态路由
        const filterRoutes = getFilterRoutes(menusList, asyncRoutes)
        // 将动态路由添加到router
        filterRoutes.forEach(route => router.addRoute(route))
        store.commit('menu/setMenuList', filterRoutes)
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      router.push('/login')
    }
  }
})
